/***********下载***********/
function fileDownload(loadUrl,id,obj){
	var arr=[]
	var dtask = null;
	var loadUrl=loadUrl;
	var id=id;
	var filename = loadUrl.substring(loadUrl.lastIndexOf("/") + 1, loadUrl.length);
	var relativePath = "_downloads/" + filename;
	console.log(relativePath)
	createDownload()
	function createDownload(){
		
		if($.inArray(id, arr)==-1){
			arr.push(id)
		}else{
			dtask = true
		}
		//判断文件是否存在
		plus.io.resolveLocalFileSystemURL(relativePath,
			function(entry){
			    if(entry.isFile){
			        plus.runtime.openFile(relativePath);
			        mui.toast('文件地址：'+entry.fullPath);
			    }
		    },
	   		function(e){dBase();}
	    );
	}
	function dBase(){
	    if(dtask){
	        mui.toast('正在下载中。。。');
	        return false;
	    }
	    mui.toast('准备下载中...')
	    obj.children('.mui-progressbar').show()
	    dtask = plus.downloader.createDownload(loadUrl,{method:'GET'},function(d,status){
			obj.children('.download-status').html('已下载')
			obj.children('.mui-progressbar').hide()
	    });
	    dtask.addEventListener("statechanged",function(task,status){
	        if(!dtask){return;}
	        switch(task.state){
	            case 1: mui.toast('开始下载...');break;//开始
	            case 2: mui.toast('下载中...');break;//链接到服务器
	            case 3:
	                var progressVal = Math.floor((task.downloadedSize/task.totalSize)*100);
                    mui(`#bar${id}`).progressbar({progress:progressVal}).show();
	                break;
	            case 4: mui.toast('下载完成');console.log(status);break;
	        }
	    });
	    dtask.start();
	}
}
/***********下载end***********/
/***********判断文件是否存在***********/
function isHaveFile(loadUrl,obj){
	var loadUrl=loadUrl;
	var filename = loadUrl.substring(loadUrl.lastIndexOf("/") + 1, loadUrl.length);
	var relativePath = "_downloads/" + filename;
	plus.io.resolveLocalFileSystemURL(relativePath,
			function(entry){
			    if(entry.isFile){
			        obj.children('.download-status').html('已下载')
			    }
		    },
	   		function(e){}
	    );
}
/***********判断文件是否存在end***********/



/***********上传图片***********/
//选取图片的来源，拍照和相册  
function showActionSheet(obj){  
      var divid = obj.id;  
      var actionbuttons=[{title:"拍照"},{title:"相册选取"}];  
      var actionstyle={title:"选择照片",cancel:"取消",buttons:actionbuttons};  
      plus.nativeUI.actionSheet(actionstyle, function(e){  
            if(e.index==1){  
                getImage(divid);  
            }else if(e.index==2){  
                galleryImg(divid);  
            }  
      } );  
} 
//调用相册
var zxjbImages=[]//在线举报文件组，需要与传值一致
function galleryImg(divid){
	plus.gallery.pick(
		function(e){
			$.each(e.files, function(k,v) {
				plus.io.resolveLocalFileSystemURL(v, 
					function(entry) {
					    compressImage(entry.toLocalURL(),entry.name,divid); 
				    }, 
				    function(e) {
					   plus.nativeUI.toast("读取拍照文件错误：" + e.message);
				    }
				);
			});
		}, 
		function ( e ) {
		},
		{
			filename: "_doc/camera/",
	   		filter:"image",
	        multiple:true
        }
	);
}
function getImage(divid) {  
    var cmr = plus.camera.getCamera();  
    cmr.captureImage(function(p) {  
        plus.io.resolveLocalFileSystemURL(p, function(entry) {  
            compressImage(entry.toLocalURL(),entry.name,divid);  
        }, function(e) {  
            plus.nativeUI.toast("读取拍照文件错误：" + e.message);  
        });  
    }, function(e) {  
    }, {  
        filename: "_doc/camera/",  
        index: 1  
    });  
}  
//压缩图片
function compressImage(url,filename,divid){  
    var name="_doc/upload/"+divid+"-"+filename;
    plus.zip.compressImage(
    	{
            src:url,//src: (String 类型 )压缩转换原始图片的路径  
            dst:name,//压缩转换目标图片的路径  
            quality:40,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100  
            overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件  
        },  
        function(event) {
            var path = name;//压缩转换目标图片的路径  
            saveimage(event.target,divid,filename,path);  
        },
        function(error) {
            plus.nativeUI.toast("压缩图片失败，请稍候再试"); 
        }
    );  
}
//保存图片
function saveimage(url,divid,name,path){  
     //alert(url);//file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg  
    //alert(path);//_doc/upload/F_ZDDZZ-1467602809090.jpg  
    var  state=0;  
    var wt = plus.nativeUI.showWaiting();  
  //  plus.storage.clear();   
    name=name.substring(0,name.indexOf("."));//图片名称：1467602809090  
    zxjbImages.push({name:name,path:path,url:url}) 
    showImgDetail(name,divid,url);  
    wt.close();  
      
}
//渲染图片
function showImgDetail (imgId,divId,src) {    
    var html = "";  
    var classname="zxjbimage-item";
    html=`
    	<div  id="${imgId}" class="${classname}">
    		<img id="picBig" data-preview-src="" data-preview-group="1" src="${src}"/>
    		<span class="del" onclick="delImg('${imgId}','${divId}')">
    			 <i class="icon iconfont icon-ziliao"></i>
    		</span>
		</div>
    `
    $(`#${divId}`).before(html);
    //delImg('${imgId}','${imgkey}');
}
//删除图片
function delImg(imgId,divId){  
    var bts = ["是", "否"];  
    plus.nativeUI.confirm("是否删除图片？", function(e) {  
            var i = e.index;  
            if (i == 0) {  
                var imgname=imgId;
                console.log(zxjbImages)
                $.each(zxjbImages,function(k,v){
                	if(v.name==imgname){
                		zxjbImages.splice(k,1)
                		$(`#${imgname}`).remove();  
                		return false
                	}
                })
                console.log(zxjbImages)
            }  
        },"请问", bts);  
}
function upDataPlus(data){
	var url=data.url ? data.url:'';
	var sendData=data.sendData ? data.sendData:'';
	var arrname=data.arrname ? data.arrname:'';
	var fileList=eval(arrname)
	if(!fileList){
		return false
	}
	var wt = plus.nativeUI.showWaiting();  
	var task = plus.uploader.createUpload(host(url),{ method:"POST"}, 
		function ( t, status ) {  
			console.log(t)
			if ( status == 200 ) {  
				mui.toast("发表成功");
				/****清空数据end****/
				clearZxjbData()
				/****清空数据end****/
				wt.close();  
			}else {  
				console.log( "上传失败:" + status);  
			}  
		}  
	);  
	$.each(sendData,function(k,v){
		task.addData(k,v); 
		console.log(k+":"+v)
	})
//	if(zxjbImages.length>0){
    if(fileList.length>0){
    	console.log(1)
    	$.each(fileList,function(k,v){
    		var imgurl=v.url
			task.addFile(imgurl,{key:"file[]"});  
		})
    }  
	task.start();  
}
/***********上传图片end***********/